<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <!-- v-if="orgType == '1'"  -->
                <el-button type="primary" @click="oprnReconciliation">发送对账申请</el-button>
                <!-- <el-button type="primary" @click="allaccount">已对账</el-button> -->
                <el-button type="primary" @click="allprintview">预览</el-button>
                <el-button type="primary" @click="allprintview">打印</el-button>
                <el-button type="primary" @click="checkSuccess" v-if="orgType == 1">对账正确</el-button>
                
            </div>
            <div class="right-panel">
                <el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
                <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                <el-button text type="primary" @click="showCondition = !showCondition">
                    <span v-if="!showCondition">展开</span>
                    <span v-else>收起</span>
                    <vab-icon
                        class="vab-dropdown"
                        :class="{ 'vab-dropdown-active': fold }"
                        icon="arrow-up-s-line"
                    />
                </el-button>
            </div>
        </el-header>
        <el-foot v-show="showCondition">
            <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
                    <el-form-item label="业务日期" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.applyDate"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <!-- <el-form-item label="业务日期" label-width="100px">
						<el-date-picker style="width: 300px" v-model="queryList.orderTime" type="datetimerange"
							value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" range-separator="-"
							unlink-panels="true" start-placeholder="开始时间" end-placeholder="结束时间" />
                    </el-form-item>-->
                    <el-form-item label="单据编号" label-width="100px">
                        <el-input
                            placeholder="---请输入单据编号---"
                            v-model="queryList.orderCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="客户" label-width="100px">
                        <el-input
                            placeholder="---请输入客户名称---"
                            v-model="queryList.storeName"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <el-form-item label="制单人" label-width="100px">
                        <el-input
                            placeholder="---请输入制单人---"
                            v-model="queryList.documentsUser"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <el-form-item label="对账状态" label-width="100px">
                        <el-select
                            placeholder="---请选择对账状态---"
                            v-model="queryList.reconciliationStatus"
                            style="width: 300px"
                        >
                            <el-option label="---请选择对账状态---" value />
                            <el-option
                                v-for="item in optionsState"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="订单编号" label-width="100px">
						<el-input placeholder="---请输入订单编号---" v-model="queryList.salesman" style="width: 300px" />
                    </el-form-item>-->
                    <el-form-item label="订单编号" label-width="100px">
                        <el-input
                            placeholder="---请输入订单编号---"
                            v-model="queryList.applyOrderCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="订单类型" label-width="100px">
                        <el-select
                            placeholder="---请选择订单类型---"
                            v-model="queryList.receivingOrderType"
                            style="width: 300px"
                        >
                            <el-option label="---请选择订单类型---" value />
                            <el-option
                                v-for="item in receivingOrderTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收货状态" label-width="100px">
                        <el-select
                            placeholder="---收货状态---"
                            v-model="queryList.taskStatus"
                            style="width: 300px"
                        >
                            <el-option label="---收货状态---" value />
                            <el-option
                                v-for="item in taskStatusList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="物料简码" label-width="100px">
                        <el-input
                            placeholder="---请输入物料简码---"
                            v-model="queryList.materialSimpCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料编码" label-width="100px">
                        <el-input
                            placeholder="---请输入物料编码---"
                            v-model="queryList.materialCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料分类" label-width="100px">
                        <el-tree-select
                            v-model="queryList.materialTypeIds"
                            placeholder="---请选择物料分类---"
                            :props="{ label: 'label', value: 'value', children: 'children' }"
                            :data="materialTypeTree"
                            multiple
                            :render-after-expand="false"
                            show-checkbox
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="100px">
                        <el-input
                            placeholder="---请输入物料名称---"
                            v-model="queryList.materialName"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="规格型号" label-width="100px">
                        <el-input
                            placeholder="---请输入规格型号---"
                            v-model="queryList.materialSpecs"
                            style="width: 300px"
                        />
                    </el-form-item>
                </el-form>
            </vab-query-form-top-panel>
        </el-foot>

        <el-main class="nopadding">
            <scTable
                ref="mytable"
                border
                :queryType="'receiving-order/borrow-accountlist'"
                :data="listData"
                :queryList="queryList"
                :column="columnList"
                :orderList="OrderList"
                :sort-orders="['ascending', 'descending']"
                @selection-change="selectionChange"
                :summaryMethod="getSummaries"
                row-key="ReceivingOrderId"
                key="ReceivingOrderId"
                :row-class-name="setRowClass"
                show-summary
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="55" align="center"></el-table-column>

                <template
                    #applyDate="{row}"
                >{{ row.applyDate.length>10? row.applyDate.slice(0, 10):row.applyDate}}</template>
                <template #orderType="{row}">
                    还货订单
                </template>
                <template #orderCode="{row}">
                    <span class="el-span-text" @click="opPrintview(row)">{{row.orderCode}}</span>
                </template>
                <template #orderStatus="{row}">
                    {{row.reconciliationStatus=='0'?'已关账':''}}
                    {{row.reconciliationStatus=='1'?'对账正确':''}}
                    {{row.reconciliationStatus=='2'?'未对账':''}}
                    {{row.reconciliationStatus=='3'?'对账中':''}}
                    {{row.reconciliationStatus=='4'?'已发送申请':''}}
                </template>
                <template #relevanceOrderCode="{row}">
                    {{row.receivingOrderType==0?row.applyOrderCode:''}}
                    {{row.receivingOrderType==1?row.afterOrderCode:''}}
                    {{row.receivingOrderType==2?row.recoveryCode:''}}
                    {{row.receivingOrderType==3?row.giveOrderCode:''}}
                </template>
                <template #taskStatus="{row}">
                    {{row.taskStatus=='1'?'全部收货':''}}
                    {{row.taskStatus=='2'?'部分收货':''}}
                    {{row.taskStatus=='3'?'未收货':''}}
                </template>
                <el-table-column label="操作" fixed="right" align="center" width="240">
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                v-if="scope.row.reconciliationStatus!='1'"
                                text
                                type="primary"
                                size="small"
                                @click="opCheck(scope.row, scope.$index)"
                            >核对</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opPrintview(scope.row, scope.$index)"
                            >预览</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opPrintview(scope.row, scope.$index)"
                            >打印</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opShow(scope.row, scope.$index)"
                            >查看</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
    </el-container>

    <!-- 发送对账申请  -->
    <reconciliation-dialog
        v-if="dialogReconciliatio"
        ref="dialogReconciliatio"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogReconciliatio = false"
    ></reconciliation-dialog>

    <!-- 核对/查看 -->
    <check-dialog
        v-if="dialogCheck"
        ref="checkDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogCheck = false"
    ></check-dialog>

    <!-- 打印/预览 -->
    <salePrint v-if="dialogPrint" ref="printDialog" @closed="dialogPrint = false"></salePrint>
</template>

<script>
import publicjs from "@/api/model/publicjs";
import tool from "@/utils/tool";
import config from "@/config";
// import printDialog from "./print";
import checkDialog from "../storeaccount/check";
import reconciliationDialog from "../storeaccount/reconciliation";

export default {
    components: {
        publicjs,
        // printDialog,
        checkDialog,
        reconciliationDialog,
    },
    data() {
        return {
            firstIndex: 0,
            receivingOrderTypeList: [
                {
                    value: 0,
                    label: "要货订单",
                },
                {
                    value: 3,
                    label: "赠送订单",
                },
            ],
            taskStatusList: [
                {
                    value: 0,
                    label: "待收货",
                },
                {
                    value: 1,
                    label: "部分收货",
                },
                {
                    value: 2,
                    label: "全部收货",
                },
            ],
            optionsState: [
                {
                    value: 1,
                    label: "对账正确",
                },
                {
                    value: 2,
                    label: "未对账",
                },
                {
                    value: 3,
                    label: "对账中",
                },
                {
                    value: 4,
                    label: "已发送申请",
                },
            ],
            materialTypeTree: [],
            orgType: "",
            columnList: [
                {
                    prop: "applyDate",
                    label: "业务日期",
                    width: "120",
                    sortable: true,
                },
                {
                    prop: "materialName",
                    label: "物料名称",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "materialSpecs",
                    label: "规格型号",
                    width: "90",
                },
                {
                    prop: "unitName",
                    label: "单位",
                    width: "60",
                },
                {
                    prop: "qty",
                    label: "结算数量",
                    width: "110",
                    sortable: true,
                },
                {
                    prop: "price",
                    label: "结算单价",
                    width: "110",
                    sortable: true,
                },
                {
                    prop: "totalAmount",
                    label: "结算金额",
                    width: "110",
                    sortable: true,
                },
                {
                    prop: "orderType",
                    label: "关联订单类型",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "orderCode",
                    label: "单据编号",
                    width: "190",
                    sortable: true,
                },
                {
                    prop: "orderStatus",
                    label: "对账状态",
                    width: "120",
                    sortable: true,
                },
                {
                    prop: "materialCode",
                    label: "物料编码",
                    width: "120",
                    sortable: true,
                },

                {
                    prop: "documentsUser",
                    label: "制单人",
                    width: "80",
                },
                {
                    prop: "storeName",
                    label: "客户",
                    width: "120",
                },
                {
                    prop: "backGoodsOrderCode",
                    label: "关联还货单号",
                    width: "120",
                    sortable: true,
                },
                {
                    prop: "taskStatus",
                    label: "收货状态",
                    width: "90",
                },
            ],
            queryList: {
                receivingOrderType: 4,
            },
            selectionRows: [],
            showCondition: false,
            columnIndex0: "",
            columnIndex17: "",
            columnIndex15: "",
            dialogPrint: false,
            dialogCheck: false,
            dialogReconciliatio: false,
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
        };
    },
    methods: {
        resetSearch() {
            this.queryList = {
                receivingOrderType: 4,
            };
        },
        oprnReconciliation() {
            this.dialogReconciliatio = true;
            this.$nextTick(() => {
                this.$refs.dialogReconciliatio.open();
            });
            // if (this.selectionRows.length > 0) {
            // 	let uniqueArr = this.selectionRows.filter((item, index, self) =>
            // 		index === self.findIndex((t) => t.receivingOrderId === item.receivingOrderId)
            // 	);
            // 	if(uniqueArr){
            // 		this.dialogReconciliatio = true;
            // 		this.$nextTick(() => {
            // 	    this.$refs.dialogReconciliatio.setData(uniqueArr);
            //       });
            // 	}
            // }else{
            // 	this.$message.error("请选择要发送对账申请的数据");
            // }
        },
        handleSaveSuccess() {
            this.$nextTick(() => {
                this.$refs.mytable.reload();
            });
        },
        async opBindData() {
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
            // this.$refs.mytable.toggleAllSelection(); // 全选
        },
        setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }
            return "";
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
            console.log(this.selectionRows);
        },
        //核对
        opCheck(row) {
            this.dialogCheck = true;
            this.$nextTick(() => {
                this.$refs.checkDialog.setData(row);
                this.$refs.checkDialog.open("Check");
            });
        },
        //对账
        async checkSuccess() {
            if (this.selectionRows.length > 0) {
                console.log(this.selectionRows);
                let arr = [];
                let set = new Set();

                this.selectionRows.forEach((item) => {
                    if (!set.has(item.receivingOrderId)) {
                        set.add(item.receivingOrderId);
                        arr.push(item.receivingOrderId);
                    }
                });
                try {
                    var returnValue = await this.$API.auth.PostProcessApi.post(
                        "receiving-order/checkSuccess",
                        {
                            receivingOrderIds: arr,
                        }
                    );
                    if (returnValue.status == 200) {
                        await this.opBindData();
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            } else {
                this.$message.error("请选择要打印的数据");
            }
        },
        opPrintview(row) {
 console.log(row)

            this.dialogPrint = true;
            this.$nextTick(() => {
                var arr = [];
                arr.push(row);
                this.$refs.printDialog.setData(arr);
                this.$refs.printDialog.open("Show");
            });
        },
        //查看
        opShow(row) {
            this.dialogCheck = true;
            this.$nextTick(() => {
                this.$refs.checkDialog.setData(row);
                this.$refs.checkDialog.open("Show");
            });
        },
        allprintview() {
            if (this.selectionRows.length > 0) {
                this.dialogPrint = true;
                let uniqueArr = this.selectionRows.filter(
                    (item, index, self) =>
                        index ===
                        self.findIndex((t) => t.orderCode === item.orderCode)
                );
                this.$nextTick(() => {
                    this.$refs.printDialog.setData(uniqueArr);
                    this.$refs.printDialog.open("Show");
                });
            } else {
                this.$message.error("请选择要打印的数据");
            }
        },
        async allaccount() {
            // console.log("this.selectionRows:", this.selectionRows);
            // return;
            if (this.selectionRows.length > 0) {
                let uniqueArr = this.selectionRows.filter(
                    (item, index, self) =>
                        index ===
                        self.findIndex(
                            (t) => t.receivingOrderId === item.receivingOrderId
                        )
                );
                var ids = uniqueArr.map((item) => {
                    return item.receivingOrderId;
                });
                const returnValue = await this.$API.auth.PostProcessApi.post(
                    "receiving-order/account",
                    ids
                );
                if (returnValue.status == 200) {
                    this.$message.success(returnValue.msg);
                    await this.opBindData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } else {
                this.$message.error("请选择要对账的数据");
            }
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 用于标志合并列的第一行

            // 初始化firstIndex
            if (rowIndex == 0 && columnIndex == 0) {
                this.firstIndex = 0;
            }

            // 当前行占用行数
            const zyRow = row.receivingOrderItems.length;

            // 对于合并列 如果当前行索引==firstIndex
            if (columnIndex == 0 || columnIndex == 17) {
                // 合并列的第一行 占用行数=zyRow 列数=1
                if (rowIndex == this.firstIndex) {
                    // 计算合并列的第一行 计算时机为处理到合并列第一行的最后一列
                    if (rowIndex == this.firstIndex && columnIndex == 17) {
                        this.firstIndex = this.firstIndex + zyRow;
                    }
                    return {
                        rowspan: zyRow,
                        colspan: 1,
                    };
                }
                // 合并列的剩余行，不占用行数和列数
                else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }
            }
            // 非合并列 都占用一行一列
            else {
                // 计算合并列的第一行 计算时机为处理到合并列第一行的最后一列
                if (rowIndex == this.firstIndex && columnIndex == 17) {
                    this.firstIndex = this.firstIndex + zyRow;
                }
                return {
                    rowspan: 1,
                    colspan: 1,
                };
            }
        },
		//合计
        getSummaries(param) {
            const { columns, data  } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = this.selectionRows.map((item) =>
                    Number(item[column.property])
                );

                if (
                    column.property == "qty" ||
                    column.property == "totalAmount"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                }
            });
            return sums;
        },
    },
    async mounted() {
        try {
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "material-type/tree",
                {
                    status: 1,
                }
            );
            if (returnValue.status == 200) {
                this.materialTypeTree = returnValue.response;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        } catch (error) {}
        this.orgType = tool.data.get("USER_INFO").AccountType;
        await this.opBindData();
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>



